#ifndef NETCFGCPP
#define NETCFGCPP
#include <dirent.h>
#include <stdlib.h>
#include <stdio.h>
#include "NetcfgCppFunctions.h"
#include <iostream>
#include <vector>
#include <string>

using namespace std;

namespace NetcfgCpp {
	const char* CURRENT_CMD = "netcfg current";
	const std::string PROF_PATH = "/etc/network.d";
	const std::string FUNC_PATH = "/usr/lib/network/network";
	const std::string CONNECT_CMD = "profile_up";
	const std::string DISCONNECT_CMD = "profile_down";

	std::string getCurrent() {
		FILE * currentCmd = popen(CURRENT_CMD, "r");
		int buffSize = 128;
		char buffer[buffSize];
		std::string currentProfile = "";
		while(!feof(currentCmd)) {
			if(fgets(buffer, buffSize, currentCmd) != NULL)
				currentProfile += buffer;
		}
		pclose(currentCmd);
		if(currentProfile != "") currentProfile.erase(currentProfile.length() - 1, 2);
		//TODO: Find a better way to get rid of the endline.
		return currentProfile;
	}

	bool isConnected() {
		if(getCurrent() == "") return false;
		else return true;
	}

	bool connect(std::string profile) {
		int extStatus = -999;
		const char* cmd = (". " + FUNC_PATH + " && " + CONNECT_CMD + " " + profile).c_str(); 	

		printf("%s\n",cmd);
		extStatus = system(cmd);
		if(extStatus == 0) return true;
		else return false;
	}

	bool disconnect(std::string profile) {
		int extStatus = -999;
		const char* cmd = (". " + FUNC_PATH + " &" + "& " + DISCONNECT_CMD + " " + profile).c_str();
		printf("%s\n",cmd);
		extStatus = system(cmd);
		if(extStatus == 0) return true;
		else return false;
	}
	
	std::vector<string> getProfiles() {
		DIR* dir = opendir(PROF_PATH.c_str());
		struct dirent *DirEntry;
		std::vector<std::string> profiles;
		while((DirEntry = readdir(dir))) {
			if(strcmp(DirEntry->d_name,".") && strcmp(DirEntry->d_name,"..") 
				&& DirEntry->d_type == 0x8) {
			std::string name = std::string(DirEntry->d_name);
			profiles.push_back(name);
			}
		}	
		closedir(dir);
		return profiles;
	}
}
#endif
